package com.coco.controller;

import com.coco.config.JwtProperties;
import com.coco.entity.UserInfo;
import com.coco.model.CommentsInfo;
import com.coco.service.CommentsService;
import com.coco.utils.CookieUtils;
import com.coco.utils.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author GHOSTLaycoo
 * @date 2020/5/27 - 10:11
 */
@EnableConfigurationProperties(JwtProperties.class)
@RestController
@RequestMapping("/comments")
public class CommentsController {

    @Autowired
    private CommentsService commentsService;

    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("新增数据")
    @PostMapping("/save")
    public ResponseEntity<Integer> save(@RequestBody CommentsInfo commentsInfo, HttpServletRequest request){
        String cookieValue = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        UserInfo infoFromToken = null;
        try {
            infoFromToken = JwtUtils.getInfoFromToken(cookieValue, jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        commentsInfo.setUserId(infoFromToken.getId());
        int result =  commentsService.save(commentsInfo);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("查询")
    @GetMapping("/selectComments/{id}")
    public ResponseEntity<List<CommentsInfo>> selectComments(@PathVariable("id") String id){
        List<CommentsInfo> commentsInfos = commentsService.selectComments(id);
        return ResponseEntity.ok(commentsInfos);
    }
}
